import myAxios from 'axios'

// Token 存储的 key
const TOKEN_KEY = 'auth_token';

// 获取 token
export const getToken = (): string | null => {
    return localStorage.getItem(TOKEN_KEY);
};

// 设置 token
export const setToken = (token: string): void => {
    localStorage.setItem(TOKEN_KEY, token);
};

// 移除 token
export const removeToken = (): void => {
    localStorage.removeItem(TOKEN_KEY);
};

// create an axios instance
const service = myAxios.create({
    // baseURL: idDev ? 'http://localhost:8080/partner' : 'http://120.26.146.100:8080/api',
    // baseURL: 'http://120.26.146.100:8082/partner',
    // baseURL: 'http://120.26.146.100:8082',
    baseURL: 'http://localhost:8080/partner',
    // baseURL: 'http://localhost:8082',
    // baseURL: 'http://localhost:20000',//配置了网关反向代理
    // baseURL: 'http://120.26.146.100:20000',//配置了网关反向代理
    // baseURL: 'http://localhost:9090',
    // baseURL: 'https://8996z1i200.goho.co/api/',
    timeout: 15000, // request timeout
})

// request interceptor - 添加 token 到请求头
service.interceptors.request.use(
    (config: any) => {
        // 从 localStorage 获取 token
        const token = getToken();
        if (token) {
            // 在请求头中添加 token，格式：Authorization: Bearer {token}
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    (error: any) => {
        // do something with request error
        console.log('请求错误:', error);
        return Promise.reject(error);
    }
)

// response interceptor
service.interceptors.response.use(
    (response: any) => {
        const res = response.data;
        console.log("我收到请求响应了", res);
        
        // 处理登录响应，保存 token
        // 登录接口返回格式：{ code: 0, data: { user: {...}, token: "..." } }
        // 兼容旧格式：{ code: 200, data: { user: {...}, token: "..." } }
        if ((res.code === 0 || res.code === 200) && res.data && res.data.token) {
            setToken(res.data.token);
            console.log("Token 已保存");
        }
        
        return res;
    },
    (error: any) => {
        console.log('响应错误:', error);
        
        // 处理 401 未授权错误（token 过期或无效）
        if (error.response) {
            const status = error.response.status;
            const res = error.response.data;
            
            // 401 未授权或 token 过期
            if (status === 401 || (res && (res.code === 40100 || res.code === 401))) {
                // 清除 token
                removeToken();
                
                // 跳转到登录页
                const redirectUrl = window.location.href;
                window.location.href = `/?redirect=${encodeURIComponent(redirectUrl)}`;
                
                return Promise.reject(new Error(res?.message || '未登录或登录已过期，请先登录'));
            }
        }
        
        return Promise.reject(error);
    }
)

export default service;
